package cc.iteachyou.template.utils;

import cc.iteachyou.template.dom.VirtualDOMElementNode;
import cc.iteachyou.template.dom.VirtualDOMNode;
import cc.iteachyou.template.dom.VirtualDOMTextNode;
import cc.iteachyou.template.dom.VirtualDOMTree;

import java.util.List;

public class RendererHelper {
    private static RendererHelper helper = null;

    /**
     * 构造函数
     */
    private RendererHelper() {
    }

    /**
     * 获取模板引擎助手实例
     *
     * @return
     */
    public static RendererHelper getInstance() {
        if (helper == null) {
            helper = new RendererHelper();
        }
        return helper;
    }

    public String render(VirtualDOMTree virtualDOM) {
        StringBuilder html = new StringBuilder();

        List<VirtualDOMNode> tree = virtualDOM.getTree();

        html.append(virtualDOM.getDocType().getDocType());

        cascadeGenerateHTML(html, tree);

        return html.toString();
    }

    private void cascadeGenerateHTML(StringBuilder html, List<VirtualDOMNode> nodes) {
        t: for (int i = 0;i < nodes.size();i++) {
            VirtualDOMNode node = nodes.get(i);
            if (node instanceof VirtualDOMElementNode) {
                VirtualDOMElementNode element = (VirtualDOMElementNode) node;
                html.append(element);
            } else if (node instanceof VirtualDOMTextNode) {
                VirtualDOMTextNode element = (VirtualDOMTextNode) node;
                html.append(element);
            }
        }
    }
}
